{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "0-5iVn0K0xiY"
   },
   "source": [
    "# Expanding\n",
    "In this lesson, you will generate customer service emails that are tailored to each customer's review.\n",
    "pip install dotenv panel  -i https://pypi.tuna.tsinghua.edu.cn/simple\n",
    "## Setup"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "id": "kLkOjk7z02YA"
   },
   "outputs": [],
   "source": [
    "from openai import OpenAI\n",
    "import os\n",
    "\n",
    "from dotenv import load_dotenv, find_dotenv\n",
    "_ = load_dotenv(find_dotenv())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "client = OpenAI(api_key=\"sk-7bec1e1708dd4d1abfbdd6f0238d3add\", base_url=\"https://api.deepseek.com\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "id": "o0Z99r4t04Bu"
   },
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "non-default argument follows default argument (1063953468.py, line 1)",
     "output_type": "error",
     "traceback": [
      "\u001B[0;36m  Cell \u001B[0;32mIn[8], line 1\u001B[0;36m\u001B[0m\n\u001B[0;31m    def get_completion(prompt, model=\"deepseek-chat\", temperature):\u001B[0m\n\u001B[0m                                                      ^\u001B[0m\n\u001B[0;31mSyntaxError\u001B[0m\u001B[0;31m:\u001B[0m non-default argument follows default argument\n"
     ]
    }
   ],
   "source": [
    "def get_completion(prompt, model=\"deepseek-chat\", temperature=0):\n",
    "    messages = [{\"role\": \"user\", \"content\": prompt}]\n",
    "    response = client.chat.completions.create(\n",
    "        model=model,\n",
    "        messages=messages,\n",
    "        temperature=temperature, # this is the degree of randomness of the model's output\n",
    "        stream=False\n",
    "    )\n",
    "    return response.choices[0].message.content"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "etkAk-lQ06Ul"
   },
   "source": [
    "## Customize the automated reply to a customer email"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "所以，他们在11月份仍然以大约49美元的价格进行17件套系统的季节性促销，几乎是半价。但出于某种原因（可以说是价格欺诈），到了12月的第二周，同样的系统价格全部上涨到了70到89美元之间。而11件套系统的价格也比之前29美元的促销价上涨了大约10美元左右。看起来还不错，但如果你看看底座，刀片固定的部分看起来不如几年前的老版本那么好。不过我打算非常小心地使用它（例如，我先把像豆子、冰块、米饭等非常硬的东西在搅拌机中压碎，然后在我想要的份量中粉碎它们，再切换到搅拌刀片制作更细的面粉，制作冰沙时先用交叉切割刀片，如果需要更细腻/更少果肉，再用平刀片）。制作冰沙时的一个特别提示：将你计划使用的水果和蔬菜切碎并冷冻（如果使用菠菜，先稍微炖软菠菜，然后冷冻以备使用；如果制作冰沙，使用中小型食品处理器），这样可以避免在制作冰沙时加入太多冰块。大约一年后，电机开始发出奇怪的声音。我打电话给客服，但保修期已经过了，所以我不得不又买了一个。仅供参考：这类产品的整体质量已经下降，所以他们有点依赖品牌认知度和消费者忠诚度来维持销售。大约两天就收到了货。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "id": "u2qsgNkd082k"
   },
   "outputs": [],
   "source": [
    "# given the sentiment from the lesson on \"inferring\",\n",
    "# and the original customer message, customize the email\n",
    "sentiment = \"negative\"\n",
    "\n",
    "# review for a blender\n",
    "review = f\"\"\"\n",
    "So, they still had the 17 piece system on seasonal \\\n",
    "sale for around $49 in the month of November, about \\\n",
    "half off, but for some reason (call it price gouging) \\\n",
    "around the second week of December the prices all went \\\n",
    "up to about anywhere from between $70-$89 for the same \\\n",
    "system. And the 11 piece system went up around $10 or \\\n",
    "so in price also from the earlier sale price of $29. \\\n",
    "So it looks okay, but if you look at the base, the part \\\n",
    "where the blade locks into place doesn’t look as good \\\n",
    "as in previous editions from a few years ago, but I \\\n",
    "plan to be very gentle with it (example, I crush \\\n",
    "very hard items like beans, ice, rice, etc. in the \\ \n",
    "blender first then pulverize them in the serving size \\\n",
    "I want in the blender then switch to the whipping \\\n",
    "blade for a finer flour, and use the cross cutting blade \\\n",
    "first when making smoothies, then use the flat blade \\\n",
    "if I need them finer/less pulpy). Special tip when making \\\n",
    "smoothies, finely cut and freeze the fruits and \\\n",
    "vegetables (if using spinach-lightly stew soften the \\ \n",
    "spinach then freeze until ready for use-and if making \\\n",
    "sorbet, use a small to medium sized food processor) \\ \n",
    "that you plan to use that way you can avoid adding so \\\n",
    "much ice if at all-when making your smoothie. \\\n",
    "After about a year, the motor was making a funny noise. \\\n",
    "I called customer service but the warranty expired \\\n",
    "already, so I had to buy another one. FYI: The overall \\\n",
    "quality has gone done in these types of products, so \\\n",
    "they are kind of counting on brand recognition and \\\n",
    "consumer loyalty to maintain sales. Got it in about \\\n",
    "two days.\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "id": "UkBgueo10_98"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "**Subject:** Thank You for Your Feedback  \n",
      "\n",
      "Dear Valued Customer,  \n",
      "\n",
      "Thank you for taking the time to share your detailed review. We sincerely apologize for the disappointment you experienced with the pricing changes and the quality of the product, particularly with the blade base and motor issues. We understand how frustrating it can be when a product doesn’t meet expectations, especially after relying on it for tasks like blending and food preparation.  \n",
      "\n",
      "We regret that the warranty had expired when you reached out to customer service. If you have any further concerns or need assistance, please don’t hesitate to contact our customer service team directly. We’re here to help and would like to ensure your experience with us improves moving forward.  \n",
      "\n",
      "Thank you again for your honest feedback. It helps us identify areas where we can do better.  \n",
      "\n",
      "Best regards,  \n",
      "AI Customer Agent\n"
     ]
    }
   ],
   "source": [
    "prompt = f\"\"\"\n",
    "You are a customer service AI assistant.\n",
    "Your task is to send an email reply to a valued customer.\n",
    "Given the customer email delimited by ```, \\\n",
    "Generate a reply to thank the customer for their review.\n",
    "If the sentiment is positive or neutral, thank them for \\\n",
    "their review.\n",
    "If the sentiment is negative, apologize and suggest that \\\n",
    "they can reach out to customer service. \n",
    "Make sure to use specific details from the review.\n",
    "Write in a concise and professional tone.\n",
    "Sign the email as `AI customer agent`.\n",
    "Customer review: ```{review}```\n",
    "Review sentiment: {sentiment}\n",
    "\"\"\"\n",
    "response = get_completion(prompt)\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "1AifxNhb1D3q"
   },
   "source": [
    "## Remind the model to use details from the customer's email\n",
    "### Note: \n",
    "We're also going to use another one of the models input \n",
    "parameters called temperature and this kind of allows \n",
    "you to vary the kind of degree of exploration and variety in \n",
    "the kind of models responses.\n",
    "\n",
    "This time the temperature is set to 0.7"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "id": "DDmCZ_AS1Fmf"
   },
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "get_completion() got an unexpected keyword argument 'temperature'",
     "output_type": "error",
     "traceback": [
      "\u001B[0;31m---------------------------------------------------------------------------\u001B[0m",
      "\u001B[0;31mTypeError\u001B[0m                                 Traceback (most recent call last)",
      "Cell \u001B[0;32mIn[7], line 16\u001B[0m\n\u001B[1;32m      1\u001B[0m prompt \u001B[38;5;241m=\u001B[39m \u001B[38;5;124mf\u001B[39m\u001B[38;5;124m\"\"\"\u001B[39m\n\u001B[1;32m      2\u001B[0m \u001B[38;5;124mYou are a customer service AI assistant.\u001B[39m\n\u001B[1;32m      3\u001B[0m \u001B[38;5;124mYour task is to send an email reply to a valued customer.\u001B[39m\n\u001B[0;32m   (...)\u001B[0m\n\u001B[1;32m     14\u001B[0m \u001B[38;5;124mReview sentiment: \u001B[39m\u001B[38;5;132;01m{\u001B[39;00msentiment\u001B[38;5;132;01m}\u001B[39;00m\n\u001B[1;32m     15\u001B[0m \u001B[38;5;124m\"\"\"\u001B[39m\n\u001B[0;32m---> 16\u001B[0m response \u001B[38;5;241m=\u001B[39m \u001B[43mget_completion\u001B[49m\u001B[43m(\u001B[49m\u001B[43mprompt\u001B[49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[43mtemperature\u001B[49m\u001B[38;5;241;43m=\u001B[39;49m\u001B[38;5;241;43m0.7\u001B[39;49m\u001B[43m)\u001B[49m\n\u001B[1;32m     17\u001B[0m \u001B[38;5;28mprint\u001B[39m(response)\n",
      "\u001B[0;31mTypeError\u001B[0m: get_completion() got an unexpected keyword argument 'temperature'"
     ]
    }
   ],
   "source": [
    "prompt = f\"\"\"\n",
    "You are a customer service AI assistant.\n",
    "Your task is to send an email reply to a valued customer.\n",
    "Given the customer email delimited by ```, \\\n",
    "Generate a reply to thank the customer for their review.\n",
    "If the sentiment is positive or neutral, thank them for \\\n",
    "their review.\n",
    "If the sentiment is negative, apologize and suggest that \\\n",
    "they can reach out to customer service. \n",
    "Make sure to use specific details from the review.\n",
    "Write in a concise and professional tone.\n",
    "Sign the email as `AI customer agent`.\n",
    "Customer review: ```{review}```\n",
    "Review sentiment: {sentiment}\n",
    "\"\"\"\n",
    "response = get_completion(prompt, temperature=0.7)\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "rvGm7Y-P2ScZ"
   },
   "source": [
    "In general, when building applications \n",
    "where you want a kind of predictable response, \n",
    "I would recommend using temperature zero. \n",
    "\n",
    "If you're trying to build a system that is \n",
    "reliable and predictable, you should go with 0. If you're trying to \n",
    "kind of use the model in a more creative way where you \n",
    "might kind of want \n",
    "a kind of wider variety of different outputs, \n",
    "you might want to use a higher temperature.\n",
    "\n",
    "So, to summarise, at higher temperatures, \n",
    "the outputs from the model are kind of more random. \n",
    "You can almost think of it as that at higher temperatures, \n",
    "the assistant is more distractible, but maybe more creative. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "aNhnWrGm1Y-g"
   },
   "source": [
    "## Try experimenting on your own!"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "authorship_tag": "ABX9TyNexIf5BABA92lckGF2ITHM",
   "provenance": []
  },
  "kernelspec": {
   "display_name": "les2",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
